#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Monox
 @Email: 627201584@qq.com
 @FileName: main.py
 @DateTime: 2023/2/23 15:19
 @SoftWare: PyCharm
"""
import PySimpleGUI as sg
import InternalExecution as IE
from datetime import datetime
import xlwt
import readXML


class GBA_dolphin:
    def __init__(self, XML_list):
        """
        云授权信息初始化
        入参为 XML_list = [dolphin_dic, GYIT_dic, GYkey_dic]
        """

        self.Version = XML_list[0].get('Version')
        self.DueDate = XML_list[0].get('DueDate')
        self.GYtenantcode = XML_list[1].get('GYtenantcode')
        self.GYtenantname = XML_list[1].get('GYtenantname')
        self.GYenvironment = XML_list[1].get('GYenvironment')
        self.GYurl = XML_list[2].get('GYurl')
        self.GYappkey = XML_list[2].get('GYappkey')
        self.GYsecret = XML_list[2].get('GYsecret')
        self.GYsessionkey = XML_list[2].get('GYsessionkey')
        DueDate_time = datetime.strptime(self.DueDate, '%Y-%m-%d').date()  # 到期日期
        self.nowday = datetime.now().date()
        self.TimeRemaining = int((DueDate_time - self.nowday).days)
        print(f'实例化成功,租户为：{self.GYtenantname}')

    def GUI_main(self,):
        """
        002
        软件主函数
        """
        # 首先设置窗口样式
        sg.theme('Reddit')
        # sg.theme('SystemDefaultForReal')LightGray1 Reddit
        # 创建布局
        fra_layout1 = [
            [sg.Text('租户代码', size=(10, 1)), sg.Input(self.GYtenantcode, key='-GYtenantcode-', size=(35, 1), disabled=True)],
            [sg.Text('租户名称', size=(10, 1)), sg.Input(self.GYtenantname, key='-GYtenantname-', size=(35, 1), disabled=True)],
            [sg.Text('租户环境', size=(10, 1)),
             sg.Input(self.GYenvironment, key='-GYenvironment-', size=(35, 1), disabled=True)],
            [sg.Btn('登陆', key='-Login-')]
        ]
        fra_layout2 = [
            [sg.Text('版本号', size=(10, 1)), sg.Text(self.Version, size=(35, 1))],
            [sg.Text('到期日期', size=(10, 1)), sg.Input(self.DueDate, size=(35, 1), disabled=True)],
            [sg.Text('剩余时间', size=(10, 1)), sg.Input(str(self.TimeRemaining) + '天', size=(35, 1), disabled=True)]
        ]
        layout1 = [[sg.Frame(title='管易云授权信息', layout=fra_layout1)],
                   [sg.Frame(title='软件信息', layout=fra_layout2)]]
        # 窗口实例化 并设置窗口名，把布局内容放进去
        window1 = sg.Window('湾豚自动新增退货单管易专版', layout1, font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
        # 进入WIN1窗口循环
        while True:
            event, values = window1.read()  # 读取窗口所有内容，event为动作
            print("event:", event, "values:", values)
            if event == '-Login-':
                if self.TimeRemaining < 0:
                    sg.popup('软件已到期，请联系售后续费', title='湾豚', font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
                else:
                    window1.Hide()
                    Format_List = ['排重物流单号', '不排重物流单号']
                    huanhuo_List = ['新增换货类型订单', '不新增换货类型订单']
                    fra1 = [
                        # sg.InputText(visible=False, key='-xiazai-'), sg.FileSaveAs('下载模板', target='-xiazai-')
                        [sg.Text('导入文件'), sg.InputText(size=(54, 1), key='-daoru-'),
                         sg.FileBrowse("导入", disabled=False, key='-Import-', size=(5, 1),
                                       file_types=(('EXCEL', '.xls'),))],
                        [sg.Text('批量备注'),
                         sg.InputText(default_text=str(self.nowday) + '工具导入', size=(54, 1), key='-remarks-')],
                        [sg.Text('仓库代码'), sg.InputText(size=(54, 1), key='-warehousein_code-')],
                        [sg.Text('排重需求'), sg.Combo(Format_List, default_value='排重物流单号', size=(30, 1), key='-Format-')],
                        [sg.Btn('提交', size=(5, 1), disabled=False, key='-Submit-')]
                    ]
                    fra2 = [
                        # sg.InputText(visible=False, key='-xiazai-'), sg.FileSaveAs('下载模板', target='-xiazai-')
                        [sg.Text('下载目录'), sg.InputText(size=(54, 1), key='-xiazai-'),
                         sg.FileSaveAs('另存为', size=(5, 1), file_types=(('EXCEL', '.xls'),))],
                        [sg.Btn('下载', size=(5, 1))]
                    ]
                    lc = 0  # 进度条默认长度
                    fra3 = [
                        [sg.Text('任务完成进度')],
                        [sg.ProgressBar(lc, orientation='h', expand_x=True, size=(20, 20), key='progressbar'),
                         sg.Btn('清空', key='-clear-', size=(5, 1))],
                        # expand_x如果为 True，元素将自动在"X”方向展开以填充可用空间
                        [sg.ML(
                            default_text="",
                            # 默认显示的文本
                            disabled=True,
                            # 元素禁用状态设定
                            reroute_stdout=False,
                            # print语句内容会显示在此文本框内
                            reroute_cprint=True,
                            # 使用cprint将内容打印到此文本框内。详细参考sg.cprint()
                            size=(68, 20),
                            # 宽度和行高设定
                            key='-ml-'
                        )]
                    ]
                    layout2 = [[sg.B("导入退货单界面"), sg.B("下载导入模板")],
                               [sg.Frame(title='先点击导入选择文件，再点击提交', layout=fra1, key='-fra1-'),
                                sg.Frame(title='先点击另存为选择目录，再点击下载', layout=fra2, key='-fra2-', visible=False)],
                               [sg.Frame(title='任务中心', layout=fra3, key='-fra3-')],
                               ]
                    # 窗口实例化 并设置窗口名，把布局内容放进去
                    window2 = sg.Window('湾豚自动新增退货单管易专版', layout2, font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
                    # 根据key值获取到进度条
                    progress_bar = window2['progressbar']
                    Submit = window2['-Submit-']
                    Import = window2['-Import-']
                    # 进入WIN2窗口循环
                    while True:
                        event, values = window2.read()  # 读取窗口所有内容，event为动作
                        print("event:", event, "values:", values)
                        if event is None:  # WIN2窗口的右上关闭动作即None
                            break

                        if event == '下载导入模板':
                            window2['-fra2-'].update(visible=True)
                            window2['-fra1-'].update(visible=False)
                            window2['-fra3-'].update(visible=False)

                        if event == '导入退货单界面':
                            window2['-fra1-'].update(visible=True)
                            window2['-fra3-'].update(visible=True)
                            window2['-fra2-'].update(visible=False)

                        if event == '-Submit-':  # 点击提交
                            # print(values['-daoru-'])
                            # progress_bar.UpdateBar(0,100)
                            x = values['-daoru-']  # 导入路径
                            y = values['-Format-']  # 排重选择

                            if len(x) == 0 or len(y) == 0:
                                sg.popup('错误操作，注意导入文件或排重需求不能为空', title='错误', font=('微软雅黑', 10),
                                         icon='ico\GBAdolphin.ico')
                            else:
                                remarks = values['-remarks-']
                                warehousein_code = values['-warehousein_code-']
                                # print(len(x))
                                Submit.update(disabled=True)
                                Import.update(disabled=True)
                                window2['-daoru-'].update(value='')
                                # num2maint1 = threading.Thread(target=num2main, args=(x, progress_bar, remarks, window2,), daemon=True)
                                if y == '排重物流单号':
                                    try:
                                        window2.perform_long_operation(
                                            lambda: IE.paichong_main(x, progress_bar, remarks, warehousein_code,
                                                                        Submit, Import, self.GYurl, self.GYappkey,
                                                                        self.GYsecret, self.GYsessionkey), '任务已完成')
                                    except Exception as e:
                                        sg.popup('错误操作，注意导入文件不能为空，或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                                 icon='ico\GBAdolphin.ico')
                                        print("报错1：", e)
                                        Submit.update(disabled=False)
                                        Import.update(disabled=False)
                                elif y == '不排重物流单号':
                                    try:
                                        window2.perform_long_operation(
                                            lambda: IE.NO_paichong_main(x, progress_bar, remarks, warehousein_code,
                                                                        Submit, Import, self.GYurl, self.GYappkey,
                                                                        self.GYsecret, self.GYsessionkey), '任务已完成')
                                    except Exception as e:
                                        sg.popup('错误操作，注意导入文件不能为空，或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                                 icon='ico\GBAdolphin.ico')
                                        print("报错1：", e)
                                        Submit.update(disabled=False)
                                        Import.update(disabled=False)
                        if event == '下载':
                            try:
                                # print(values['-xiazai-'])
                                mbml = values['-xiazai-']
                                nwb = xlwt.Workbook('utf-8')  # 新建工作簿
                                nws = nwb.add_sheet('Sheet1')  # 新建工作表
                                nws.write(0, 0, '物流单号')
                                nwb.save(mbml)
                                sg.popup_auto_close('模板已下载', icon='ico\GBAdolphin.ico')
                            except Exception as e:
                                sg.popup('错误操作，注意下载目录不能为空，或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                         icon='ico\GBAdolphin.ico')
                                print("报错2：", e)

                        if event == '任务已完成':
                            sg.popup_auto_close('任务已完成', icon='ico\GBAdolphin.ico')
                        
                        if event == '-clear-':
                            window2['-ml-'].update('任务中心日志已清空，需要查看历史日志请打开log文件...\n')

                    window2.close()

            if event == None:  # WIN1窗口的右上关闭动作即None
                break

        window1.close()


if __name__ == '__main__':
    XML_list = readXML.read_XML()
    dolphin = GBA_dolphin(XML_list)
    dolphin.GUI_main()
